package org.spring.springboot.controller;

import java.util.List;

import javax.validation.Valid;

import org.spring.springboot.domain.City;
import org.spring.springboot.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/city")
public class CityController {
	
	
	@Autowired
	private CityService cityService;

	@RequestMapping(value = "/addcity", method = RequestMethod.GET)
	public String addcity(Model model) {
		return "addcity";
	}
	
	@RequestMapping(value = "/savecity", method = RequestMethod.POST)	
	public String createCity(@Valid City city,BindingResult result,Model model) {	
		 model.addAttribute("city",city);
	       if(result.hasErrors()){
	    	   List<ObjectError>  list = result.getAllErrors();
	           for(ObjectError  error:list){
	        	   System.out.println(error.getCode()+"----"+error.getObjectName()+"---"+error.getArguments()+"---"+error.getDefaultMessage());
	           }
	           return "error";
	       }
		cityService.saveCity(city);
		
		return "success";
	}

	@RequestMapping(value = "/upcity", method = RequestMethod.POST)
	public void modifyCity(City city) {
		cityService.updateCity(city);
	}

	@RequestMapping(value = "/delcity/{id}", method = RequestMethod.POST)
	public void modifyCity(@PathVariable("id") Long id) {
		cityService.deleteCity(id);
	}

}
